#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>

#include "cdefs.h"
#include "cfile.h"
// #include "cbuf.h"

#define FAIL(str, line) {                       \
  printf("Fail on line %d: [%s]\n", line, str); \
  return str;                                   \
}

#define ASSERT(expr) {                  \
  static_num_tests++;                   \
  if (!(expr)) FAIL(#expr, __LINE__);   \
}

#define RUN_TEST(test) {        \
    const char *msg = test();   \
    if(msg)                     \
        return msg;             \
}


static int static_num_tests = 0;


const char *test_cfile_mkdirs() {

    ASSERT(cfile_mkdirs("/tmp/test", CFILE_DEFAULT_DIR_MODE) == 0);
	ASSERT(cfile_mkdirs("", CFILE_DEFAULT_DIR_MODE) == 0);
	ASSERT(cfile_mkdirs(NULL, CFILE_DEFAULT_DIR_MODE) != 0);

	return NULL;
}

const char *test_cfile_get_filename() {
    char *p;

    p = cfile_get_filename("/mnt/hgfs/data/workspace/project/webserver-v2/start.sh");
    ASSERT(strcmp(p, "start.sh") == 0);

    p = cfile_get_filename("start");
    ASSERT(strcmp(p, "start") == 0);

    return NULL;
}


const char *test_cfile_get_suffix() {
    char *p;

    p = cfile_get_suffix("start.sh");
    ASSERT(strcmp(p, ".sh") == 0);

    p = cfile_get_suffix("start");
    ASSERT(p == NULL);

    return NULL;
}

const char *test_cfile_create() {
    int fd;


    remove("test.txt");

    fd = cfile_create("test.txt");
    ASSERT(fd >= 0);
    close(fd);

    remove("/tmp/test/test.txt");

    fd = cfile_create("/tmp/test/test.txt");
    ASSERT(fd >= 0);
    close(fd);

    return NULL;
}

const char *test_cfile_copy() {
	int ret;

	ret = cfile_copy("test_cfile.c", "test_cfile.c.2");
	ASSERT(ret == 0);

	ret = cfile_copy("test_cfile", "test_cfile.2");
	ASSERT(ret == 0);

    return NULL;
}




static const char *run_all_tests(void) {
    RUN_TEST(test_cfile_mkdirs);
    RUN_TEST(test_cfile_get_filename);
    RUN_TEST(test_cfile_get_suffix);
    RUN_TEST(test_cfile_create);
	RUN_TEST(test_cfile_copy);
    return NULL;
}

int main(void) {
    const char *fail_msg = run_all_tests();
    printf("%s, tests run: %d\n", fail_msg ? "FAIL" : "PASS", static_num_tests);
    return fail_msg == NULL ? 0 : -1;
}

